/**
 * webSocket连接
 * author: WilliamYe
 */
layui.define(function (exports) {
    var cache = layui.cache;
    if (typeof (tio) == "undefined") {
        tio = {};
    }
    tio.ws = {};
    tio.ws = function ($, layim) {

        this.heartbeatTimeout = 15000; // 心跳超时时间，单位：毫秒
        this.heartbeatSendInterval = this.heartbeatTimeout / 2;

        var self = this;

        this.connect = function () {
            // var userId = localStorage.getItem("userid");
            var url = "ws://192.168.1.24:9326?userId=" + cache.user.id;
            var socket = new WebSocket(url);

            self.socket = socket;

            socket.onopen = function () {
                console.log("tio ws 启动~");

                self.lastInteractionTime(new Date().getTime());

                //建立心跳
                self.ping();
            };

            socket.onclose = function () {
                console.log("tio ws 关闭~");

                //尝试重连
                self.reconn();
            };
            socket.onmessage = function (res) {
                console.log("接收到消息！！");
                console.log(res);
                var msgBody = eval('(' + res.data + ')');
                if (msgBody.emit === 'chatMessage') {
                    var obj = {};
                    if (msgBody.data.type === 'group') {
                        obj = {
                            username: msgBody.data.username
                            , avatar: msgBody.data.avatar
                            , id: msgBody.data.id
                            , type: msgBody.data.type
                            , content: msgBody.data.content
                        }
                    } else {
                        obj = {
                            username: msgBody.data.username
                            , avatar: msgBody.data.avatar
                            , id: msgBody.data.fromid
                            , type: msgBody.data.type
                            , content: msgBody.data.content
                        };
                        layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
                    }
                    layim.getMessage(obj);
                }

                if (msgBody.emit === 'addList') {
                    // layim.addList(msgBody.groupData); //如果是在iframe页，如LayIM设定的add面板，则为 parent.layui.layim.addList(data);
                    console.log("运行到此处");
                    window.location.reload();
                    // window.location.reload();
                }

                if (msgBody.emit === 'userStatus') {
                    if (msgBody.data.type === 'offline') {
                        layim.setFriendStatus(msgBody.data.id, 'offline');
                    } else {
                        layim.setFriendStatus(msgBody.data.id, 'online');
                    }
                }

                self.lastInteractionTime(new Date().getTime());
            }


        };

        /*this.openChatWindow = function () {

            // 获取个人信息
            $.ajax({
                url: "../chat/getMineAndGroupData",
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("X-Access-Token",
                        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTExODg3MzYsInVzZXJuYW1lIjoiYWRtaW4ifQ.TrDrTJ_JXLcLyaC7F7j2v70lwkOWowZb_YJy1w8HsKA");
                },
                async: false,
                success: function (res) {
                    console.log(self);
                    self.group = res.data.group;
                    self.mine = res.data.mine;
                    self.userId = self.mine.id;
                    // layui.layim.cache() = res.data;
                }
            });

            // console.log(self.group);
            // console.log(self.mine);
            /!*var cache =  layui.layim.cache();
            cache.mine = self.mine;
            cache.group = self.group;*!/

            var cache =  layui.layim.cache();
            cache.mine = self.mine;
            var local = layui.data('layim')[cache.group]; //获取当前用户本地数据

            //这里以删除本地聊天记录为例
            delete local;

            //向localStorage同步数据
            layui.data('layim', {
                key: cache.group
                ,value: local
            });

            // console.log(cache);

            // 打开窗口
           /!* layim.chat(self.group[0]);
            layim.setChatMin(); //收缩聊天面板*!/
        };*/

        this.sendChatMessage = function (res) {
            if (res.to.type === 'friend') {
                layim.setChatStatus('<span style="color:#FF5722;">对方正在输入。。。</span>');
            }
            self.socket.send(JSON.stringify({
                type: 'chatMessage'
                , data: res
            }));
        };

        /**
         * 改变签名
         * @param value
         */
        this.changeSign = function (value) {
            $.post("/system/user/sign",
                {
                    sign: value,
                    id: cache.user.id,
                    token: cache.user.token,
                    username: cache.user.username
                },
                function (res) {
                    layer.msg(res.message);
                })
        };

        this.initHistoryMess = function () {
            // localStorage.clear();
            $.ajax({
                url: '../chat/getGroupHistoryMsg',
                success: function (res) {
                    console.log(res);
                    var data = res.data;

                    if (data.length < 1) {
                        return;
                    }
                    console.log(data.length);
                    for (var i in data) {
                        layim.getMessage(data[i]);
                    }
                }
            });
        };


        //-----------重试机制---------------
        this.lastInteractionTime = function () {
            // debugger;
            if (arguments.length == 1) {
                this.lastInteractionTimeValue = arguments[0]
            }
            return this.lastInteractionTimeValue
        };

        this.ping = function () {
            console.log("------------->准备心跳中~");


            //建立一个定时器，定时心跳
            self.pingIntervalId = setInterval(function () {
                var iv = new Date().getTime() - self.lastInteractionTime(); // 已经多久没发消息了

                // debugger;

                // 单位：秒
                if ((self.heartbeatSendInterval + iv) >= self.heartbeatTimeout) {

                    self.socket.send(JSON.stringify({
                        type: 'pingMessage'
                        , data: 'ping'
                    }));
                    console.log("------------->心跳中~")


                }
            }, self.heartbeatSendInterval)
        };

        this.reconn = function () {
            // 先删除心跳定时器
            clearInterval(self.pingIntervalId);

            // 然后尝试重连
            self.connect();
        };

        this.joinGroup = function (res) {
            var val = {};
            val.mine = layui.layim.cache().mine;
            val.group = res;
            self.socket.send(JSON.stringify({
                type: 'group'
                , data: val
            }));
        };

        this.getGroupById = function (val) {
            $.ajax({
                url: '../chat/chatGroup/getGroupById',
                data: {
                    id: val
                },
                success: function (res) {
                    console.log(res);
                    /* res.data = {
                         type: 'group' //列表类型，只支持friend和group两种
                             ,avatar: "a.jpg" //群组头像
                         ,groupname: 'Angular开发' //群组名称
                         ,id: "12333333" //群组id
                     }*/
                    $(".layui-layim-search input").val("");
                    parent.layui.layim.addList(res.result);
                }
            });
        }


    };

    exports('tiows', {})
});

